<template>
  <div class="materials-with-cart-container" v-loading="state.exportLoading">
    <splitpanes class="default-theme">
      <!-- 左侧物资分类树 -->
      <pane size="15">
        <StoreTypeTree 
          ref="storeTypeTreeRef" 
          :data="state.storeTypeTreeData" 
          @node-click="handleCategoryChange" 
          @refresh="loadStoreTypeTree" 
        />
      </pane>

      <!-- 右侧物资信息表格 -->
      <pane size="85" style="overflow: auto">
        <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
          <!-- 搜索表单 -->
          <el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
            <el-row>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
                <el-form-item label="关键字">
                  <el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
                <el-form-item label="物资名称">
                  <el-input v-model="state.tableQueryParams.name" clearable placeholder="请输入物资名称" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
                <el-form-item label="状态">
                  <g-sys-dict v-model="state.tableQueryParams.status" code="StatusEnum" render-as="select" placeholder="请选择状态" clearable filterable />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
                <el-form-item label="库存状态">
                  <g-sys-dict v-model="state.tableQueryParams.stockStatus" code="StockStatusEnum" render-as="select" placeholder="请选择库存状态" clearable filterable />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
                <el-form-item>
                  <el-button-group style="display: flex; align-items: center">
                    <el-button type="primary" icon="ele-Search" @click="handleQuery" v-reclick="1000"> 查询 </el-button>
                    <el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
                    <el-button icon="ele-ZoomIn" @click="() => (state.showAdvanceQueryUI = true)" v-if="!state.showAdvanceQueryUI" style="margin-left: 5px"> 高级查询 </el-button>
                    <el-button icon="ele-ZoomOut" @click="() => (state.showAdvanceQueryUI = false)" v-if="state.showAdvanceQueryUI" style="margin-left: 5px"> 隐藏 </el-button>
                    
                    <!-- 购物车操作按钮 -->
                    <el-button 
                      type="success" 
                      style="margin-left: 5px" 
                      icon="ele-Plus" 
                      @click="addSelectedToCart" 
                      :disabled="state.selectData.length === 0"
                    > 
                      添加申请 ({{ state.selectData.length }}) 
                    </el-button>
                    <el-button 
                      type="warning" 
                      style="margin-left: 5px" 
                      icon="ele-ShoppingCart" 
                      @click="openCart"
                      :badge="cartTotal"
                    > 
                      购物车 
                    </el-button>
                    <el-button 
                      type="info" 
                      style="margin-left: 5px" 
                      icon="ele-Document" 
                      @click="openHistory"
                    > 
                      查看历史
                    </el-button>
                  </el-button-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <el-card class="full-table" shadow="hover" style="margin-top: 5px">
          <el-table
            :data="state.tableData"
            @selection-change="(val: any[]) => { state.selectData = val; }"
            style="width: 100%"
            v-loading="state.tableLoading"
            tooltip-effect="light"
            row-key="id"
            @sort-change="sortChange"
            border
          >
            <el-table-column type="selection" width="40" align="center" fixed="left" />
            <el-table-column type="index" label="序号" width="55" align="center" fixed="left" />
            <el-table-column prop="storeTypeId" label="分类" width="150" fixed="left" :formatter="(row: any) => row.storeTypeDisplayName" show-overflow-tooltip />
            <el-table-column prop="name" label="物资名称" width="200" fixed="left" show-overflow-tooltip />
            <el-table-column prop="unit" label="单位" show-overflow-tooltip />
            <el-table-column prop="price" label="单价" show-overflow-tooltip>
              <template #default="scope">
                <span>{{ scope.row.price ? `¥${scope.row.price.toFixed(2)}` : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="currentStock" label="库存数量" show-overflow-tooltip />
            <el-table-column prop="availableStock" label="可用库存" fixed="left" show-overflow-tooltip />
            <el-table-column prop="stockStatus" label="库存状态" fixed="left" show-overflow-tooltip>
              <template #default="scope">
                <g-sys-dict v-model="scope.row.stockStatus" code="StockStatusEnum" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center" fixed="right">
              <template #default="scope">
                <el-button 
                  type="primary" 
                  size="small" 
                  icon="ele-Plus" 
                  @click="addSingleToCart(scope.row)"
                  :disabled="mode === 'outbound' && scope.row.availableStock <= 0"
                > 
                  添加 
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-model:currentPage="state.tableParams.page"
            v-model:page-size="state.tableParams.pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            :total="state.tableParams.total"
            size="small"
            background
          />
        </el-card>
      </pane>
    </splitpanes>

    <!-- 购物车抽屉 -->
    <InboundCart v-if="mode === 'inbound'" v-model="showCart" @submit-success="handleSubmitSuccess" />
    <OutboundCart v-if="mode === 'outbound'" v-model="showCart" @submit-success="handleSubmitSuccess" />
    
    <!-- 历史记录对话框 -->
    <el-dialog
      v-model="showHistory"
      :title="mode === 'inbound' ? '入库申请历史记录' : '出库申请历史记录'"
      width="90%"
      :close-on-click-modal="false"
    >
      <InboundHistory v-if="mode === 'inbound'" />
      <OutboundHistory v-if="mode === 'outbound'" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="materialsWithCart">
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useStoreMaterialsApi } from '/@/api/store/storeMaterials';
import { useCartStore } from '/@/stores/cartStore';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

// 组件导入
import StoreTypeTree from '/@/views/store/storeMaterials/component/storeTypeTree.vue';
import InboundCart from '/@/components/cart/InboundCart.vue';
import OutboundCart from '/@/components/cart/OutboundCart.vue';
import InboundHistory from '/@/components/InboundHistory.vue';
import OutboundHistory from '/@/components/OutboundHistory.vue';

interface Props {
  mode: 'inbound' | 'outbound'; // 模式：入库或出库
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'inbound',
});

const emit = defineEmits<{
  'submit-success': [];
}>();

const storeMaterialsApi = useStoreMaterialsApi();
const cartStore = useCartStore();
const storeTypeTreeRef = ref();
const showCart = ref(false);
const showHistory = ref(false);

const state = reactive({
  exportLoading: false,
  tableLoading: false,
  showAdvanceQueryUI: false,
  dropdownData: {} as any,
  selectData: [] as any[],
  storeTypeTreeData: [] as any[],
  currentCategoryId: 0,
  tableQueryParams: {} as any,
  tableParams: {
    page: 1,
    pageSize: 20,
    total: 0,
    field: 'createTime',
    order: 'descending',
    descStr: 'descending',
  },
  tableData: [],
});

// 购物车总数计算
const cartTotal = computed(() => {
  return props.mode === 'inbound' ? cartStore.inboundTotal : cartStore.outboundTotal;
});

// 页面加载时
onMounted(async () => {
  await loadStoreTypeTree();
  await handleQuery();
});

// 加载物资分类树数据
const loadStoreTypeTree = async () => {
  try {
    const data = (await storeMaterialsApi.getDropdownData(true).then((res) => res.data.result)) ?? {};
    state.dropdownData.storeTypeId = data.pid || [];
    state.storeTypeTreeData = data.pid || [];
  } catch (error) {
    console.error('加载物资分类树失败:', error);
    ElMessage.error('加载物资分类失败');
  }
};

// 分类节点点击事件
const handleCategoryChange = (node: any) => {
  const nodeId = node.id || node.value || 0;
  state.currentCategoryId = nodeId;
  state.tableParams.page = 1;
  
  if (nodeId === 0 || nodeId === '0') {
    delete state.tableQueryParams.storeTypeId;
  } else {
    state.tableQueryParams.storeTypeId = nodeId;
  }
  handleQuery();
};

// 查询操作
const handleQuery = async (params: any = {}) => {
  state.tableLoading = true;
  try {
    state.tableParams = Object.assign(state.tableParams, params);
    const queryParams = Object.assign({}, state.tableQueryParams, state.tableParams, {
      status: 1, // 只显示启用状态的物资
    });
    const result = await storeMaterialsApi.page(queryParams).then((res) => res.data.result);
    state.tableParams.total = result?.total;
    state.tableData = result?.items ?? [];
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('查询失败');
  } finally {
    state.tableLoading = false;
  }
};

// 重置查询
const resetQuery = () => {
  state.tableQueryParams = {};
  state.currentCategoryId = 0;
  nextTick(() => {
    storeTypeTreeRef.value?.setCurrentKey(0);
  });
  handleQuery();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  state.tableParams.pageSize = val;
  state.tableParams.page = 1;
  handleQuery();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  state.tableParams.page = val;
  handleQuery();
};

// 列排序
const sortChange = async (column: any) => {
  state.tableParams.field = column.prop;
  state.tableParams.order = column.order;
  await handleQuery();
};

// 添加选中的物资到购物车
const addSelectedToCart = () => {
  if (state.selectData.length === 0) {
    ElMessage.warning('请先选择物资');
    return;
  }

  // 转换为购物车项目格式
  const cartItems = state.selectData.map((material: any) => ({
    materialId: material.id,
    materialName: material.name,
    storeTypeId: material.storeTypeId,
    storeTypeName: material.storeTypeDisplayName,
    unit: material.unit,
    price: material.price || 0,
    quantity: 1,
    maxStock: material.currentStock || 0,
    availableStock: material.availableStock || 0,
  }));

  // 根据模式添加到对应购物车并获取返回信息
  let addedItems: any[] = [];
  if (props.mode === 'inbound') {
    addedItems = cartStore.addToInboundCart(cartItems);
  } else {
    addedItems = cartStore.addToOutboundCart(cartItems);
  }

  // 根据返回信息显示不同的消息
  const newItems = addedItems.filter(item => item.isNew);
  const updatedItems = addedItems.filter(item => !item.isNew);
  
  let message = '';
  if (newItems.length > 0) {
    message += `新增 ${newItems.length} 个物资`;
  }
  if (updatedItems.length > 0) {
    if (message) message += '，';
    message += `更新 ${updatedItems.length} 个物资数量`;
  }
  message += ' 到申请购物车';
  
  ElMessage.success(message);
  
  // 清空选择
  state.selectData = [];
};

// 添加单个物资到购物车
const addSingleToCart = (material: any) => {
  // 出库模式下检查库存
  if (props.mode === 'outbound' && material.availableStock <= 0) {
    ElMessage.error('该物资可用库存不足');
    return;
  }

  const cartItem = {
    materialId: material.id,
    materialName: material.name,
    storeTypeId: material.storeTypeId,
    storeTypeName: material.storeTypeDisplayName,
    unit: material.unit,
    price: material.price || 0,
    quantity: 1,
    maxStock: material.currentStock || 0,
    availableStock: material.availableStock || 0,
  };

  // 根据模式添加到对应购物车并获取返回信息
  let addedItems: any[] = [];
  if (props.mode === 'inbound') {
    addedItems = cartStore.addToInboundCart([cartItem]);
  } else {
    addedItems = cartStore.addToOutboundCart([cartItem]);
  }

  // 显示对应的消息
  const addedItem = addedItems[0];
  if (addedItem.isNew) {
    ElMessage.success(`已添加 ${material.name} 到申请购物车`);
  } else {
    ElMessage.success(`${material.name} 数量已增加 ${addedItem.quantity} 个`);
  }
};

// 打开购物车
const openCart = () => {
  if (cartTotal.value === 0) {
    ElMessage.info('购物车是空的，请先选择物资');
    return;
  }
  showCart.value = true;
};

// 打开历史记录
const openHistory = () => {
  showHistory.value = true;
};

// 提交成功回调
const handleSubmitSuccess = () => {
  emit('submit-success');
  // 刷新物资列表以更新库存信息
  handleQuery();
};
</script>

<style scoped>
.materials-with-cart-container {
  height: calc(100vh - 84px);
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
  width: 100%;
}

:deep(.splitpanes__pane) {
  overflow: hidden;
}

:deep(.splitpanes__splitter) {
  background-color: var(--el-border-color-light);
  position: relative;
  opacity: 0.7;
}

:deep(.splitpanes__splitter:hover) {
  opacity: 1;
  background-color: var(--el-color-primary);
}

/* 购物车按钮的徽章样式 */
:deep(.el-button .el-badge) {
  position: absolute;
  top: -8px;
  right: -8px;
}
</style>